package cn.zld.sh.sh;

import android.app.Presentation;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Response;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import cn.zld.sh.sh.base.BaseApplication;
import cn.zld.sh.sh.ui.home.HomeFragment;
import cn.zld.sh.sh.ui.renwu.RenwuFragment;
import cn.zld.sh.sh.ui.userfragment.UserFragment;
import cn.zld.sh.sh.ui.settingfragment.SettingFragment;
import cn.zld.sh.sh.url.HttpUrls;
import cn.zld.sh.sh.util.LogUtils;
import cn.zld.sh.sh.util.OkHttpClientManager;
import cn.zld.sh.sh.util.SharedUtils;
import cn.zld.sh.sh.util.ToastUtils;

public class MainActivity extends AppCompatActivity {

    private Context myContext;

    private Fragment[] fragments;
    private RenwuFragment renwuFragment;
    private SettingFragment settingFragment;
    private UserFragment userFragment;
    private int lastfragment;//用于记录上个选择的Fragment
    private Handler handler = new Handler();
    private String newVersion = "version_error";

    private long exitTimeMillis = 0; //选择返回键的时长


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
//                    if (getSupportActionBar()!=null){
//                        getSupportActionBar().hide();
//                    }
                    switchFragment(lastfragment,0);
                    lastfragment=0;
                    return true;
                case R.id.navigation_dashboard:
//                    if (getSupportActionBar()!=null){
//                        getSupportActionBar().show();
//                    }
                    switchFragment(lastfragment,1);
                    lastfragment=1;
                    return true;
                case R.id.navigation_notifications:
//                    if (getSupportActionBar()!=null){
//                        getSupportActionBar().show();
//                    }
                    switchFragment(lastfragment,2);
                    lastfragment=2;
                    return true;
            }
            return false;
        }
    };

    private void switchFragment(int lastfragment,int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.hide(fragments[lastfragment]);//隐藏上个Fragment
        if (fragments[index].isAdded() == false) {
            transaction.add(R.id.mainview, fragments[index]);


        }
        transaction.show(fragments[index]).commitAllowingStateLoss();

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myContext = this;
//        if (getSupportActionBar()!=null){
//            getSupportActionBar().hide();
//        }

        checkVersion();

//        Vibrate(1000);
//        playvoid(R.raw.qdm);
//        destroy();
    }

    private final Runnable task = new Runnable() {
        @Override
        public void run() {
            AlertDialog.Builder builder=new AlertDialog.Builder(myContext);

            builder.setTitle("有新版本");
            if(newVersion.equals("version_error")){
                builder.setMessage("版本号错误！");
                builder.setCancelable(false);
                builder.create().show();
                return;
            }else if(newVersion.equals("update")){
                ;
                builder.setMessage("有新版本了，快去更新吧^v^");
                builder.setCancelable(false);
                builder.setPositiveButton("去更新", null);
                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(HttpUrls.UPDATEURL));
                        startActivity(viewIntent);//一定要记得从apkName=后面这个位置也要修改包名
                    }
                });
                return;
            }
            init();
        }
    };



    private void checkVersion(){
        new Thread(){

            @Override
            public void run() {
                try{
                    PackageManager manager = myContext.getPackageManager();

                    PackageInfo info = manager.getPackageInfo(myContext.getPackageName(), 0);

                    Response response = OkHttpClientManager.getAsyn(HttpUrls.GetVersion + "?version=" + info.versionName);
                    String html = response.body().string();
                    JSONObject jo = new JSONObject(html);
                    newVersion = jo.getString("msg");
                    handler.post(task);
                }catch (Exception e){
                    LogUtils.d(e.toString());
                    handler.post(task);
                }
            }
        }.start();
    }

    private void init(){
        myContext= getApplicationContext();
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        renwuFragment = new RenwuFragment();
        settingFragment = new SettingFragment();
        userFragment = new UserFragment();
        fragments = new Fragment[]{renwuFragment, settingFragment, userFragment};
        lastfragment=0;

//        getSupportFragmentManager().beginTransaction().replace(R.id.mainview,homeFragment).show(homeFragment).commit();
        String token = SharedUtils.getString("token", "");
        if(token.isEmpty()){
            SharedUtils.clearData();
            Intent intent = new Intent();
            intent.setClass(myContext, LoginActivity.class);
            startActivity(intent);
        }else{
            new UserFragment().getUinfo(false);
        }
        switchFragment(lastfragment, 0);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //返回提示：
        if(keyCode==KeyEvent.KEYCODE_BACK){
            long  currentTime=System.currentTimeMillis();
            if(currentTime-exitTimeMillis==0||currentTime-exitTimeMillis>2000){
                exitTimeMillis=System.currentTimeMillis();
                ToastUtils.showMessage("再按一次退出程序");
                return false;
            }
            else{
                BaseApplication.getApplication().exit();
            }
        }
        return super.onKeyDown(keyCode, event);
    }//Keydown

    private String loadJs(){
        try {
            //Return an AssetManager instance for your application's package
            InputStream is = getResources().getAssets().open("main.js");
            int size = is.available();
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            // Convert the buffer into a string.
            String text = new String(buffer, "utf-8");
            // Finally stick the string into the text view.
            return text;
        } catch (IOException e) {
            // Should never happen!
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return "";
    }


}
